package com.sc.nft.helper;

import cn.hutool.http.HttpRequest;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 物流查询
 */
@Component
public class LogisticsQuery {

    @Value("${logistics.secretId}")
    private String secretId;
    @Value("${logistics.secretKey}")
    private String secretKey;
    @Value("${logistics.source}")
    private String source;

    public static String calcAuthorization(String source, String secretId, String secretKey, String datetime)
            throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
        Mac mac = Mac.getInstance("HmacSHA1");
        Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());
        mac.init(sKey);
        byte[] hash = mac.doFinal(signStr.getBytes("UTF-8"));
        String sig = new BASE64Encoder().encode(hash);

        String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"" + sig + "\"";
        return auth;
    }

    public static String urlencode(Map<?, ?> map) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(String.format("%s=%s",
                    URLEncoder.encode(entry.getKey().toString(), "UTF-8"),
                    URLEncoder.encode(entry.getValue().toString(), "UTF-8")
            ));
        }
        return sb.toString();
    }


    @SneakyThrows
    public String   get(String logisticsId,String tel){
        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String datetime = sdf.format(cd.getTime());
        // 签名
        String auth = calcAuthorization(source, secretId, secretKey, datetime);
        // 请求头
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("X-Source", source);
        headers.put("X-Date", datetime);
        headers.put("Authorization", auth);

        // 查询参数
        Map<String, String> queryParams = new HashMap<String, String>();
        queryParams.put("kddh",logisticsId);
        queryParams.put("tel",tel);
        // url参数拼接
        String url = "https://service-e9nwx4zy-1251114020.gz.apigw.tencentcs.com/release/way";
        if (!queryParams.isEmpty()) {
            url += "?" + urlencode(queryParams);
        }
        return HttpRequest.get(url).headerMap(headers,Boolean.TRUE).execute().body();
    }

    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String datetime = sdf.format(cd.getTime());
        // 签名
        String auth = calcAuthorization("market-2al97xx8a", "AKIDL5gq294c2o4czf6Cn3p31YJs3Enc6k21Oxd", "9FihFauqJ8lXeQrTBvmBAl0j3fgqhkl8HbqXt5pt", datetime);
        // 请求头
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("X-Source", "market-2al97xx8a");
        headers.put("X-Date", datetime);
        headers.put("Authorization", auth);

        // 查询参数
        Map<String, String> queryParams = new HashMap<String, String>();
        queryParams.put("kddh","78761518823791");
        // url参数拼接
        String url = "https://service-e9nwx4zy-1251114020.gz.apigw.tencentcs.com/release/way";
        if (!queryParams.isEmpty()) {
            url += "?" + urlencode(queryParams);
        }
        System.out.println(HttpRequest.get(url).headerMap(headers,Boolean.TRUE).execute().body());
    }
}
